<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
        *{padding: 0;margin:0;}
        body {
            background:url(images/bg.jpg) left top repeat;
        }
        .tip{
		  text-align: center;
		  font-size: 36px;
		}
		.tip .black{
		  color:black;
		}
		.tip .white{
		  color:white;
		}

		.sider{
          position: absolute;
          left:50%;
          margin-left: 340px;
        }

        .sider b{
          font-size: 20px;
          -webkit-user-select:none;
          -moz-user-select:none;
          user-select:none;
        }

    </style>
    <script type="text/javascript">
    	var totalData = [];
        var counts = 0;
        var canvas;
        var context;
        var isWhite = true;//设置是否该轮到白棋
        var isWell = false;//设置该局棋盘是否赢了，如果赢了就不能再走了
        var img_b = new Image();
        img_b.src = "images/b.png";//黑棋图片
        var img_w = new Image();
        img_w.src = "images/w.png";//白棋图片
 
        var chessData = new Array(225).fill(0);//这个为棋盘的一维数组用来保存棋盘信息，初始化0为没有走过的，1为白棋走的，2为黑棋走的
        
 
        function drawRect() {//页面加载完毕调用函数，初始化棋盘
            canvas = document.getElementById("canvas");
            context = canvas.getContext("2d");
 			
            for (var i = 0; i <= 640; i += 40) {//绘制棋盘的线
                context.beginPath();
                context.moveTo(0, i);
                context.lineTo(640, i);
                context.closePath();
                context.stroke();
 
                context.beginPath();
                context.moveTo(i, 0);
                context.lineTo(i, 640);
                context.closePath();
                context.stroke();
            }
        }
        function play(e) {//鼠标点击时发生
        	var _top = document.getElementById("canvas").offsetTop,
        	    _left = document.getElementById("canvas").offsetLeft;
            var x = parseInt((e.clientX - 20- _left) / 40);//计算鼠标点击的区域，如果点击了（65，65），那么就是点击了（1，1）的位置
            var y = parseInt((e.clientY - 20 - _top) / 40);
            
            //判断是否悔棋后再下的子，如果是则恢复当前counts对应的chessData
            if(counts < totalData.length && counts){
                // var _chessData = totalData[counts-1].chessClone;
                // for (var k = 0; k < chessData.length; k++) {
                //     chessData[k] = _chessData[k];
                // }
                totalData.splice(counts,totalData.length-counts);
            }
            //判断该位置是否被下过了
            if (chessData[x+15*y] != 0) {
                return;
            }
            counts += 1;
            // 克隆 chessData,避免数组更新后totalData内所有的chessData都更新
            var chessClone = new Array(225);
            for (var k = 0; k < chessData.length; k++) {
                chessClone[k] = chessData[k];
            }
            if (isWhite) {
                isWhite = false;
                totalData.push({chess:1,x,y});
                drawChess(1, x, y);
            }
            else {
                isWhite = true;
                totalData.push({chess:2,x,y});
                drawChess(2, x, y);
            } 
        }
        function drawChess(chess, x, y) {//参数为，棋（1为白棋，2为黑棋），数组位置
            if (isWell == true) {
                alert("已经结束了，如果需要重新玩，请刷新");
                return;
            }
            if (x >= 0 && x < 15 && y >= 0 && y < 15) {
                if (chess == 1) {
                    context.drawImage(img_w, x * 40 + 20, y * 40 + 20);//绘制白棋
                    chessData[x+15*y] = 1;
                }
                else {
                    context.drawImage(img_b, x * 40 + 20, y * 40 + 20);
                    chessData[x+15*y] = 2;
                }
                judge(x, y, chess);
            }
        }
        function judge(x, y, chess) {//判断该局棋盘是否赢了
            var count1 = 0;
            var count2 = 0;
            var count3 = 0;
            var count4 = 0;
            if(chess == 2){
                document.getElementById('chessName').innerHTML = "白子";
                document.getElementById('chessName').className = 'white';
            }else{
                document.getElementById('chessName').innerHTML = "黑子";
                document.getElementById('chessName').className = 'black';
            }
            //左右判断

            for (var i = x; i >= 0; i--) {
                if (chessData[i+15*y] != chess) {
                    break;
                }
                count1++;
            }
            for (var i = x + 1; i < 15; i++) {
                if (chessData[i+15*y] != chess) {
                    break;
                }
                count1++;
            }
            //上下判断
            for (var i = y; i >= 0; i--) {
                if (chessData[x+15*i] != chess) {
                    break;
                }
                count2++;
            }
            for (var i = y + 1; i < 15; i++) {
                if (chessData[x+15*i] != chess) {
                    break;
                }
                count2++;
            }
            //左上右下判断
            for (var i = x, j = y; i >= 0 && j >= 0; i--, j--) {
                if (chessData[i+15*j] != chess) {
                    break;
                }
                count3++;
            }
            for (var i = x + 1, j = y + 1; i < 15 && j < 15; i++, j++) {
                if (chessData[i+15*j] != chess) {
                    break;
                }
                count3++;
            }
            //右上左下判断
            for (var i = x, j = y; i >= 0 && j < 15; i--, j++) {
                if (chessData[i+15*j] != chess) {
                    break;
                }
                count4++;
            }
            for (var i = x + 1, j = y - 1; i < 15 && j >= 0; i++, j--) {
                if (chessData[i+15*j] != chess) {
                    break;
                }
                count4++;
            }
            if (count1 >= 5 || count2 >= 5 || count3 >= 5 || count4 >= 5) {
                if (chess == 1) {
                    alert("白棋赢了");
                }
                else {
                    alert("黑棋赢了");
                }
                isWell = true;//设置该局棋盘已经赢了，不可以再走了
            }
        }
        function backGame(){
            if(counts < 2) return;
            chessData = new Array(225).fill(0);
            counts -= 1;
            isWell = false;
        	context.clearRect(0,0,640,640);
        	drawRect();
            isWhite = !isWhite;
        	for(var i = 0; i < counts; i++){
        		(function(arg){
        			drawChess(totalData[arg].chess,totalData[arg].x,totalData[arg].y);
			   })(i);
        	}
        }
        function regainGame(){
            if(counts > totalData.length-1) return;
            counts += 1;
            isWhite = !isWhite;
            for(var i = 0; i < counts; i++){
                (function(arg){
                    drawChess(totalData[arg].chess,totalData[arg].x,totalData[arg].y);
               })(i);
            }
        }
        function beginGame(){
            history.go(0);
        }
    </script>
</head>
<body onload="drawRect()">
    <div>
    	<div class="tip">
            <span id="chessName">白子</span>玩家下子
        </div>
        <div class="sider">
            <b onmousedown="backGame()">悔棋</b><br/><br/><br/><b onmousedown="regainGame()">恢复</b><br/><br/><br/><b onmousedown="beginGame()">重开</b>
        </div>
        <canvas width="640" id="canvas" onmousedown="play(event)" height="640" style="margin:0 auto;display: block;background: url(images/wood.jpg) left top repeat;">你的浏览器不支持HTML5 canvas  ，请使用 google chrome 浏览器 打开.
        </canvas>
    </div>
 
</body>
</html>